package com.gjy.netty.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-11-15 14:05:45
 */
public class FileChannel1 {

    private static final Logger logger = LoggerFactory.getLogger(FileChannel1.class);
    private static final String FILE = "D:\\code\\java\\special-topic\\encryption\\src\\main\\resources\\file-channel.txt";

    public static void main(String[] args) {

        try (RandomAccessFile file = new RandomAccessFile(FILE, "rw")) {
            FileChannel fileChannel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(5);
            do {
                int len = fileChannel.read(buffer);
                logger.info("读到的字节数: {}", len);
                if (len == -1)
                    break;
                buffer.flip();
                while (buffer.hasRemaining()) {
                    logger.info("{}", (char) buffer.get());
                }
                buffer.clear();
            } while (true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
